<div class="layui-card">
    <div class="layui-card-body">
        <form lay-filter="addCustomerProductForm" id="addCustomerProductForm" class="layui-form model-form"
              style="padding: 0px 10px 0px 0px">
            <div class="layui-row table-bor storageWorkIsSelect" style="margin-top: 0px">
                <span>客户与订单信息：</span>
                <table class="layui-table" id="customerTable2" lay-filter="customerTable2"></table>
            </div>

            <div class="layui-row table-bor storageWorkIsSelect" style="margin-top: 20px">
                <span>客户物料信息：</span>
                <!--<table class="layui-table" id="customerProductTable" lay-filter="customerProductTable"></table>-->
                <table class="layui-table" id="customeProTable">
                    <thead>
                    <tr>
                        <th style="text-align: center">客户物料名称</th>
                        <th style="text-align: center">客户物料编号</th>
                        <th style="text-align: center">客户规格码</th>
                        <th style="text-align: center">上传附件</th>
                        <th style="text-align: center">是否需要包装</th>
                        <th style="text-align: center">包装说明</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td><!--客户物料名称-->
                            <input type="text" name="extProductName" id="extProductName"
                                   placeholder="请输入客户物料名称"
                                   autocomplete="off" class="layui-input customClass"
                                   style="text-align: center">
                        </td>
                        <td><!--客户物料编号-->
                            <input type="text" name="extProductCode" id="extProductCode"
                                   placeholder="请输入客户物料编号"
                                   autocomplete="off" class="layui-input customClass"
                                   style="text-align: center">
                        </td>
                        <td><!--客户规格码-->
                            <input type="text" name="extSpecCode" id="extSpecCode"
                                   placeholder="请输入客户规格码"
                                   autocomplete="off" class="layui-input customClass"
                                   style="text-align: center">
                        </td>
                        <td><!--上传附件-->
                            <div id="btnUploadExt" class="layui-btn" style="float: left;"><i
                                    class="layui-icon">&#xe681;</i>上传文件
                            </div>
                            <div id="btnUploadExt_path" class="uploadImgStyle"
                                 style="margin-left: 50px;line-height: 40px;"></div>
                            <input id="btnUploadExt_file" name="enclosure" type="hidden"/>
                        </td>
                        <td><!--是否需要包装-->
                            <select name="packing" id="packing" lay-filter="packing"
                                    style="text-align: center; line-height: 30px; height: 30px;">
                                <option value="">请选择是否需要包装</option>
                                <option value="0">需要</option>
                                <option value="1">不需要</option>
                            </select>
                        </td>
                        <td><!--包装说明-->
                            <input type="text" name="packingRequire" id="packingRequire"
                                   placeholder="请输入包装说明" autocomplete="off"
                                   class="layui-input customClass" style="text-align: center">
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="layui-form-item text-right" style="padding-top: 10px;">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
                <button class="layui-btn" type="button" lay-filter="addCustomerProductSubmit"
                        id="addCustomerProductSubmit" lay-submit>提交
                </button>
            </div>
        </form>
    </div>
</div>
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'upload', 'laydate', 'laytpl'], function () {
        $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var laytpl = layui.laytpl;


        let addCustomerProductListData = [], specificationCode = [];
        let cacheParameters = {productTypeId: ''}; //保存请求参数,防止同一参数多次请求

        //客户信息
        table.render({
            elem: '#customerTable2',
            url: config.base + 'enterprise/sell/admin/customersInfo/list',
            where: {id: c_data.id},
            page: false,
            cellMinWidth: 100,
            cols: [[
                {field: 'customerName', align: 'center', title: '客户名称'}
                , {field: 'id', align: 'center', title: '客户编码'}
                , {
                    field: '',
                    align: 'center',
                    title: '客户联系人',
                    templet: '#contactNameTemplate',
                    width: 200
                }
                , {field: 'agentName', align: 'center', title: '所属渠道'}
                , {field: 'createTime', align: 'center', title: '录入时间'}
                , {field: 'creatorName', align: 'center', title: '客服代表'}
            ]],
            done: function (res, curr, count) {
                //客户联系人
                admin.req('enterprise/sell/admin/contactInfo/list', {selCustomerId: c_data.id}, function (res) {
                    if (res.code == 200) {
                        loadSelectHtml(res.data, "请选择客户联系人", "contactId", "name");
                    }
                }, 'GET');
            }
        });

        $("#ggmInp").hide();//隐藏规格码input div

        //请求物料类型
        admin.req('enterprise/product/admin/productType/getProductTypeByType', {type: 0}, function (res) {
            loadSelectHtml(res.data, "请选择物料类型", "productTypeId", "name");

            if (data) {//回显值
                $("#productTypeId").val(data.productTypeId);
                form.render('select');

                //加载基础单位
                admin.req('enterprise/product/admin/productUnit/getIsBaseUnitProductUnitByType', {
                    type: 0,
                    productTypeId: data.productTypeId
                }, function (res) {
                    $("#unitId").val(res.data.id);
                    $("#unitName").val(res.data.name);
                }, 'get');


                //包装单位
                admin.req('enterprise/product/admin/productUnit/getProductUnitByType', {
                    type: 0,
                    productTypeId: data.productTypeId
                }, function (res) {
                    loadSelectHtml(res.data, "请选择包装单位", "packUnitId", "name");
                    if (data) {
                        $("#packUnitId").val(data.packUnitId);
                        form.render('select');
                    }
                }, 'get');

                //包装方案
                admin.req('enterprise/product/admin/productPack/getByProductTypeId', {
                    type: 0,
                    productTypeId: data.productTypeId
                }, function (res) {
                    loadSelectHtml(res.data, "请选择", "productPack", "name");
                    if (data) {
                        $("#productPack").val(data.productPack);
                        form.render('select');
                    }
                }, 'get');


                //客户联系人
                admin.req('enterprise/sell/admin/contactInfo/list', {
                    selCustomerId: data.customerId,
                    id: data.contactId
                }, function (res) {
                    loadSelectHtml(res.data, "请选择", "contactId", "name");
                    $("#contactId").val(data.contactId);
                    form.render('select');
                }, 'GET');

                $("input[name='remark']").val(data.remark);
                $("input[name='skuCode']").val(data.skuCode);
                $("input[name='skuName']").val(data.skuName);
                $("input[name='weight']").val(data.weight);

                //客户物料信息
                $("input[name='extProductName']").val(data.extProductName);
                $("input[name='extProductCode']").val(data.extProductCode);
                $("input[name='extSpecCode']").val(data.extSpecCode);

                if (data.packing) {
                    let select = 'dd[lay-value=0]';
                    $('#packing').siblings("div.layui-form-select").find('dl').find(select).click();
                } else {
                    let select = 'dd[lay-value=1]';
                    $('#packing').siblings("div.layui-form-select").find('dl').find(select).click();
                }

                $("input[name='packingRequire']").val(data.packingRequire);

                //**设置禁止选择：**//
                $("#packing").attr("disabled", "disabled");
                $(".customClass").attr("disabled", "disabled");
                $(".customClass").attr("style", "background-color: #EEEEEE;");//设置input为灰色背景

                $("#categoryDiv").css("pointer-events", "none");//物料分类禁选

                $("#btnUploadExt").hide();//隐藏上传按钮
                $("#addCustomerProductSubmit").hide();//隐藏提交按钮

                $("#ggm").hide();//隐藏规格码 table div
                $("#ggmInp").show();//显示规格码 input div
                $("#specValueNames").val(data.skuSpecValueNames);
                $("#specValueNames").show();

            }
        }, 'get');

        form.on('select(productTypeId)', function (data) {
            //加载基础单位
            admin.req('enterprise/product/admin/productUnit/getIsBaseUnitProductUnitByType', {
                type: 0,
                productTypeId: data.value
            }, function (res) {
                $("#unitId").val(res.data.id);
                $("#unitName").val(res.data.name);
            }, 'get');

            //包装单位
            admin.req('enterprise/product/admin/productUnit/getProductUnitByType', {
                type: 0,
                productTypeId: data.value
            }, function (res) {
                console.log(res.data);
                loadSelectHtml(res.data, "请选择", "packUnitId", "name");
                if (data) {
                    $("#packUnitId").val(data.packUnitId);
                    form.render('select');
                }
            }, 'get');

            //包装方案
            admin.req('enterprise/product/admin/productPack/getByProductTypeId', {productTypeId: data.value}, function (res) {
                loadSelectHtml(res.data, "请选择", "productPack", "name");
                if (data) {
                    $("#productPack").val(data.productPack);
                    form.render('select');
                }
            }, 'get');

            if (cacheParameters.productTypeId == $("#productTypeId").val()) {
                addCustomerProductListData = [];
                addCustomerProductListData.push({
                    index: 1,
                    isShow: true,
                    specificationCode: specificationCode,
                    skuSpecValueNames: []
                })
            } else {
                cacheParameters.productTypeId = $('#productTypeId').val();
                addCustomerProductListData = [];
                //规格数据
                admin.reqSync('enterprise/product/admin/productSpec/getProductSpecByProductTypeId', {productTypeId: data.value}, res => {
                    if (res.code === 200) {
                        specificationCode = res.data;
                    }
                }, 'get');

                addCustomerProductListData.push({
                    index: 1,
                    isShow: true,
                    specificationCode: specificationCode,
                    skuSpecValueNames: []
                })
            }

            table.reload('specValue', {data: addCustomerProductListData});
            console.log("addCustomerProductListData:" + addCustomerProductListData);

        });

        //物料系列
        admin.req('enterprise/product/admin/product/list', {}, function (res) {
            loadSelectHtml(res.data, "请选择物料系列", "productRange", "name");
            if (data) {
                $("#productRange").val(data.productRange);
                form.render('select');

                admin.req('enterprise/product/admin/product/getProductById', {productId: data.productRange}, function (res) {
                    $("#rangeCode").val(res.data.productCode)
                }, 'get');
            }
        });
        //物料系列编码
        form.on('select(productRange)', function (data) {
            admin.req('enterprise/product/admin/product/getProductById', {productId: data.value}, function (res) {
                $("#rangeCode").val(res.data.productCode)
            }, 'get');
        });

        //规格码
        let addSelfCollectedGoodsTbList = table.render({
            elem: '#specValue',
            page: false,
            cellMinWidth: 110,
            data: addCustomerProductListData,
            limit: Number.MAX_VALUE,
            height: 180,
            cols: [[
                {
                    field: '', width: '500', templet: d => {
                        let selectHTML = '', skuSpecValueNamesValue = '', skuSpecValueNamesString = '';
                        d.skuSpecValueNames.forEach(item => skuSpecValueNamesString += item.name + '-');
                        selectHTML += `<span id="skuSpan" style="display:${d.isShow == true ? 'none' : ''}">${skuSpecValueNamesString.substring(0, skuSpecValueNamesString.length - 1)}</span>`;

                        d.specificationCode.forEach((item, index) => {
                            let skuSpecValueNamesValueSelect = '';
                            selectHTML += `<div class="skuSpecValueNames" style="width: calc((100% - 30px) / 3);float: left;margin:5px; display:${d.isShow == true ? '' : 'none'}">
                                                       <select class="skuSpecValueNamesList"  name="${d.index + '-' + item.id}" id="${d.index + '-' + item.id}" style="margin-bottom: 5px" lay-search="">`;
                            selectHTML += '<option value="">' + item.name + '</option>';
                            if (d.skuSpecValueNames[index]) {
                                skuSpecValueNamesValue = d.skuSpecValueNames[index].value;
                            } else {
                                skuSpecValueNamesValue = '';
                            }
                            item.productSpecValueList.forEach(itemList => {
                                if (skuSpecValueNamesValue == itemList.id) {
                                    skuSpecValueNamesValueSelect = 'selected=""'
                                } else {
                                    skuSpecValueNamesValueSelect = ''
                                }
                                if (item.specCode == 'is') {
                                    if (item.specLocation == 'last') {
                                        selectHTML += '<option ' + skuSpecValueNamesValueSelect + ' value="' + itemList.id + '" skuSpec="' + item.id + '" >' + itemList.value + item.specHead + '</option>'
                                    } else {
                                        selectHTML += '<option ' + skuSpecValueNamesValueSelect + ' value="' + itemList.id + '" skuSpec="' + item.id + '" >' + item.specHead + itemList.value + '</option>'
                                    }

                                } else {
                                    selectHTML += '<option ' + skuSpecValueNamesValueSelect + ' value="' + itemList.id + '" skuSpec="' + item.id + '" >' + itemList.value + '</option>'
                                }
                            });

                            selectHTML += '</select></div>';

                        });
                        return selectHTML;
                    }
                }
            ]],
            done: function (res, curr, count) {

            }
        });


        //加载物料分类树级菜单
        var arr2tree;
        admin.req('enterprise/product/admin/productCategory/getProductCategoryByType', {type: 0}, function (res) {
            for (let i = 0; i < res.data.length; i++) {
                res.data[i].children = [];
            }
            arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
        }, 'get', false);

        var selectedData = function (treeData, targetId) {

            for (var k = 0; k < treeData.length; k++) {
                var nodeId = treeData[k].id;
                if (targetId == nodeId) {
                    treeData[k].selected = true;
                    return;
                } else {
                    if (treeData[k].children && treeData[k].children != '') {
                        selectedData(treeData[k].children, targetId);
                    }
                }
            }
        }

        if (data) {
            selectedData(arr2tree, data.productCategoryId);
        }

        var smlSelectInstans = xmSelect.render({
            el: '#productCategoryId',
            model: {label: {type: 'text'}},
            radio: true,
            clickClose: true,
            filterable: true,
            tree: {
                show: true,
                strict: false,
                expandedKeys: [-1],
            },
            tips: '请选择物料分类',
            prop: {
                name: 'name',
                value: 'id',
                children: 'children'
            },
            data() {
                //填充数据
                return arr2tree;
            },
            on(data) {
                let parentId = data.arr.length > 0 ? data.change[0].id : -1;
                $("input[name='productCategoryId']").val(parentId);
            }
        });

        //上传附件
        uploadImg("btnUploadExt", "btnUploadExt_path", "btnUploadExt_file");
        if (data && data.enclosure) {
            $('#btnUploadExt_path').html('<img src="' + data.enclosure + '" style="height: 35px;margin-right: 100px;" />');
            layer.photos({
                photos: '.uploadImgStyle'
                , anim: 5
            });
        }

        form.val('addCustomerProductFrom', data);
        // 表单提交事件
        form.on('submit(addCustomerProductSubmit)', function (d) {
            layer.load(2);
            let skuData = [], extProductData = [], listDataObj = {};
            let skuObj = {};
            let extProduct = {};
            let row = $("[lay-id=specValue] table tbody tr");
            let skuString = '', skuSpecValueString = '', skuSpecString = '';
            for (let i = 0; i < row.length; i++) {
                for (let j = 0; j < row.eq(i).find(".skuSpecValueNames").find('select').length; j++) {
                    if (row.eq(i).find(".skuSpecValueNames").find('input').eq(j).val() == '') {
                        skuString = '';
                        skuSpecValueString = '';
                        skuSpecString = '';
                    } else {
                        skuString += row.eq(i).find(".skuSpecValueNames").find('input').eq(j).val() + '-';
                        skuSpecValueString += row.eq(i).find(".skuSpecValueNames").find('option:selected').eq(j).val() + '_';
                        skuSpecString += row.eq(i).find(".skuSpecValueNames").find('option:selected').eq(j).attr('skuspec') + '_';
                    }
                }
            }
            let skuSpecValueNames = skuString.substring(0, skuString.length - 1);
            let skuSpecValue = skuSpecValueString.substring(0, skuSpecValueString.length - 1);
            let skuSpec = skuSpecString.substring(0, skuSpecString.length - 1);
            //alert("skuSpecValueNames:"+skuSpecValueNames+"   skuSpecValue"+skuSpecValue);
            //取值
            var contactId = $("#contactId").val();
            var extProductName = addCustomerProductForm.extProductName.value;
            var extProductCode = addCustomerProductForm.extProductCode.value;
            var extSpecCode = addCustomerProductForm.extSpecCode.value;
            var enclosure = addCustomerProductForm.enclosure.value;
            var packing = $("#packing").val();//获取是否包装当前选择项值
            if (packing == 1 || !packing) {
                packing = false;
            } else {
                packing = true;
            }

            var packingRequire = addCustomerProductForm.packingRequire.value;
            var productTypeId = $("#productTypeId").val();
            var productCategoryId = addCustomerProductForm.productCategoryId.value;
            var productRange = $("#productRange").val();
            /* var rangeCode = addCustomerProductForm.rangeCode.value;
             var unitId = document.getElementById("unitId").value;*/
            var remark = addCustomerProductForm.remark.value;
            var skuCode = addCustomerProductForm.skuCode.value;
            var skuName = addCustomerProductForm.skuName.value;
            var packUnitId = $("#packUnitId").val();
            var productPack = $("#productPack").val();
            var weight = addCustomerProductForm.weight.value;

            /*var options=$("# option:selected");//获取当前选择项.
            options.val();//获取当前选择项的值.*/

            //赋值
            skuObj = {
                skuCode: skuCode,
                skuName: skuName,
                oldSpecCode: extSpecCode,
                unitId: packUnitId,
                packId: productPack,
                skuSpecValueNames: skuSpecValueNames,
                skuSpecValue: skuSpecValue,
                skuSpec: skuSpec,
                productTypeId: productTypeId,
                productCategoryId: productCategoryId,
                productId: productRange,
                remark: remark,
                weightNumber: weight
            };

            extProduct = {
                name: extProductName,
                code: extProductCode,
                spec: extSpecCode,
                hasPack: packing,
                packInstructions: packingRequire
            }

            skuData.push(skuObj);
            extProductData.push(extProduct);
            console.log("skuData: " + skuData);
            console.log("extProductData: " + extProductData);

            listDataObj.productDetailForm = skuData;
            listDataObj.externalProductForm = extProductData;
            listDataObj.customerId = c_data.id;
            listDataObj.contactId = contactId;
            listDataObj.skuCode = skuCode;
            listDataObj.enclosure = enclosure;
            listDataObj.extProductCode = extProductCode;
            console.log("listDataObj: " + listDataObj);

            admin.req('enterprise/sell/admin/customerProductCatalog/addProduct', JSON.stringify(listDataObj), function (res) {
                layer.closeAll('loading');
                if (res.code === 200) {
                    layer.closeAll();
                    layer.msg(res.msg, {icon: 1});
                    table.reload('customerProductCatalogTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST', true, 'application/json; charset=utf-8');
        });
    })
</script>